#!/usr/bin/env python
# coding: utf-8

"""
For NSP --

This module is a simple case for support execute command from a text format command file.

the difference between this case and cmdcase is this case support mutiple ne.

Copyright (c) 2005-2009 UTStarcom, Inc.

2007-06-14, jbzeng@utstar.com.
"""

# from onshs import BaseCase
from .basecase import BaseCase
import re
import os
import sys

class MNECMDCase (BaseCase):
    OPTIONS = [
        {
            'opt' : '--cmd-file',
            'dest': 'cmd_file',
            'metavar' : 'FILENAME',
            'help' : 'the file name of command text',
            'required' : True,
        },
    ]
    
    def __init__(self) :
        self.cmd = []
        self.testnes = {}
        self.curne = ''
        self.lastne =''
        self.read = {}
        self.default_split_flag = ':::'
        self.split_flag = ''
        BaseCase.__init__(self)

    def execute(self) :
        nr = NetRing()
        curne = ''
        self.__get_split_flag(self.options.cmd_file)
        #print 'default_split_flag:',self.default_split_flag
        #print 'split_flag:',self.split_flag
        #print self.options
        self.cmd = nr.parse_cmd_file(self.options.cmd_file)
        
        #print "****************"
        #print self.cmd
        #print "****************"
        
        for cmditem in self.cmd:
            #print "cmditem:",cmditem
            self.read.clear()
            self.read.update({"lastne":''})
            #internal cmd
            if re.match("&&&",cmditem['cmd'])!=None:
                cmd=cmditem['cmd'][3:]
                cmdtemp = cmd.split(self.split_flag)
                #print "cmdtemp",cmdtemp
                if len(cmdtemp) < 3:
                    realcmd = cmdtemp[0]
                    if re.search('connect',cmd) != None:
                        nr1 = NetRing()
                        curne = nr1
                        self.curne = nr1
                        self.lastne = nr1
                        self.read.update({"lastne":''})
                    else:
                        curne = self.curne
                else:
                    #print cmd
                    if re.search('connect',cmd)!=None:
                        nr1 = NetRing()
                        curne = nr1
                        self.testnes.update({cmdtemp[1]:nr1})
                        realcmd = cmdtemp[2]
                        self.curne = nr1
                        self.lastne = nr1
                        self.read.update({'lastne':''})
                    else:
                        curne = self.testnes[cmdtemp[1]]
                        realcmd = cmdtemp[2]

                #print "*"*10
                #print 'self.testnes:',self.testnes
                #print 'realcmd:',realcmd
                #print 'self.lastne:',self.lastne                
                #print "*"*10
                if not curne.execute_cmd(realcmd):
                    break
      
                continue
            #send command
            else:
                #print '\n',cmditem['cmd']
                #print "+"*10
                #print 'self.lastne:',self.lastne  
                cmd=cmditem['cmd']
                cmdtemp = cmd.split(self.split_flag)
                #print "cmdtemp",cmdtemp
                if len(cmdtemp) < 3:
                    curne = self.lastne
                    realcmd = cmdtemp[0]
                    key = 'lastne'
                else:
                    #print cmd
                    curne = self.testnes[cmdtemp[1]]
                    realcmd = cmdtemp[2]
                    key = cmdtemp[1]

                #print "*"*10
                #print self.testnes
                #print realcmd
                #print "*"*10
                sendne = curne
                rst=curne.send(realcmd,5)
                #match the expected value      
                if len(cmditem['exp'])==0 and len(cmditem['!exp'])==0:
                    continue
                    #expitem="r - success"
                    #expobj=re.search(expitem,rst)
                    #if expobj==None:
                    #    self.__nook_exit()
      
                self.read.update({key:rst})
                
                for expitem in cmditem['exp']:                  
                    exptemp = expitem.split(self.split_flag)
                    #print "exptemp",exptemp
                    if len(exptemp) < 3:
                        curne = self.lastne
                        realexp = exptemp[0]
                        key = 'lastne'
                    else:
                        curne = self.testnes[exptemp[1]]
                        realexp = exptemp[2]
                        key = exptemp[1]
                    
                    expne = curne                  
                    if expne != sendne:
                        # if self.read.has_key(key) == False or (self.read.has_key(key) == True and self.read[key] == ''):
                        if (key in self.read) == False or ((key in self.read) == True and self.read[key] == ''):
                            expneoutput = expne.read(3)
                            self.read.update({key:expneoutput})
                    
                    realexpoutput = self.read[key]                        
                    
                    #print 'realexpoutput:',realexpoutput
                    expobj=re.search(realexp,realexpoutput)
                    if expobj==None:
                        self.__nook_exit()
            
                for noexpitem in cmditem['!exp']:
                    noexptemp = noexpitem.split(self.split_flag)
                    #print "noexptemp",noexptemp
                    if len(noexptemp) < 3:
                        curne = self.lastne
                        norealexp = noexpitem[0]
                        key = 'lastne'
                    else:
                        curne = self.testnes[noexptemp[1]]
                        norealexp = noexptemp[2]
                        key = noexptemp[1]
                    
                    expne = curne                    
                    if expne != sendne:
                        # if(self.read.has_key(key) == False or(self.read.has_key(key) == True and self.read[key] == '')):
                        if((key in self.read) == False or((key in self.read) == True and self.read[key] == '')):
                            expneoutput = expne.read(3)
                            self.read.update({key:expneoutput})

                       
                    realexpoutput = self.read[key]
                    expobj=re.search(norealexp,realexpoutput)
                    if expobj!=None:
                        self.__nook_exit()
            
        self.__ok_exit()


    def __ok_exit(self):
        self.logger.info("Congratulations! %s executed successufully!" % self.options.cmd_file)
        self.succ_exit()
    def __nook_exit(self):
        self.logger.warning("Case (%s) was failed, and will exit!"%self.options.cmd_file) # 杈撳嚭鍒版棩蹇�
        self.failed_exit()        


    def __get_split_flag(self,cmd_file):
       case_dir = os.path.split(sys.argv[0])[0]
       cmd_dir = 'cmd'
       cmd_path = os.path.normpath(os.path.join(case_dir,cmd_dir,cmd_file))
       f = open(cmd_path) 
       line = ''
       expobj = ''
       
       while 1:
           line = f.readline()
           expobj = re.search('^[\s|]*\n',line)
           if expobj == None:
               break;

       f.close()
       expobj = re.search('^#!',line)
       if expobj != None:
           self.split_flag = self.default_split_flag
           return
       expobj = re.search('^#.*split_flag[ |]*=[ |]*"(.*)"',line)
       if expobj != None:
           a = expobj.group(1)
           self.split_flag = a
       else:
           self.split_flag = self.default_split_flag
           
           
       
if __name__ == "__main__" :
    case = MNECMDCase()
    case.execute()
    